<template>
	<view class="container">
		<u-navbar :custom-back="back" :back-text-style="{ color: '#000', fontSize: '16px' }" back-icon-name="null" back-text="返回" :border-bottom="false" :background="navBarBackground" title-color="#fff">
			<!-- #ifndef MP -->
			<view slot="right" class="navbar-submit-btn" @tap.stop="prepareData">发表</view>
			<!-- #endif -->
		</u-navbar>
		<textarea class="tip-textarea" v-model="content" placeholder-class="tip-textarea-placeholder" placeholder="想说点什么呢～" :maxlength="contentMaxlength"></textarea>
		<view class="tip-count">{{ content.length || 0 }} / {{ contentMaxlength }}</view>
		<view class="upload-chunk">
			<view class="pre-box">
				<template v-if="!videoData.src">
					<view class="pre-item" v-for="(item, index) in fileList" :key="index">
						<image class="pre-item-image" :src="item.base64 || item.url" mode="aspectFill" @tap.stop="previewImage" :data-index="index"></image>
						<view class="delete-icon" @tap.stop="deleteUploadItem(index)"><u-icon name="close" size="18" color="#ffffff"></u-icon></view>
						<view class="edit-btn" @tap.stop="editImage" :data-index="index">编辑</view>
						<view class="upload-mask" style="{height: `(${100 - item.progress})%`}" v-if="item.progress > 0 && !item.error">{{ item.progress }}%</view>
						<!--  -->
						<view class="upload-error" v-if="item.error"><u-icon name="error" color="red" size="70"></u-icon></view>
					</view>
				</template>
				<u-upload
					:class="{ hide: videoData.src }"
					@on-uploaded="onUploaded"
					:max-count="uploadMaxLength"
					:form-data="formData"
					:before-upload="beforeUpload"
					:header="uploadHeader"
					:name="keyName"
					:auto-upload="false"
					ref="uUpload"
					:action="action"
					:custom-btn="true"
					:show-upload-list="false"
				>
					<view slot="addBtn" class="upload-add-btn">
						<text class="upload-add-icon suifont sui-zhaopian"></text>
						<view class="upload-add-btn-text">添加照片</view>
					</view>
				</u-upload>
				<view class="upload-add-btn" :class="{ hide: fileList.length > 0 || videoData.src }" @tap.stop="chooseVideo" :style="{ marginLeft: '20rpx' }">
					<text class="upload-add-icon suifont sui-shipin"></text>
					<view class="upload-add-btn-text">添加视频</view>
				</view>
				<view class="video-preview" v-if="videoData.src">
					<!--  -->
					<video
						id="momentVideo"
						ref="momentVideo"
						class="video-player"
						@fullscreenchange="onVideoFullscreen"
						:show-center-play-btn="false"
						:controls="videoStatus"
						object-fit="cover"
						:src="videoData.src"
						:class="{ horizontal: videoData.width > videoData.height, vertical: videoData.width < videoData.height }"
					>
						<cover-image class="video-btn" src="@/static/images/moment/icon-video-play.png" @click="playVideo"></cover-image>
						<cover-view class="video-del" @click="delVideo">删除</cover-view>
					</video>
				</view>
			</view>
		</view>
		<u-cell-group :border="false">
			<!--  -->
			<u-cell-item :icon-style="cellIconStyle" :arrow="!location.name" @click="chooseLocation" :title-style="cellTitleStyle" :icon-size="50" :border-top="true" icon="map-fill" :title="location.name || '所在位置'">
				<view @tap.stop="deleteLocation" v-if="location.name" slot="right-icon"><u-icon name="close" color="#F85962"></u-icon></view>
			</u-cell-item>
		</u-cell-group>
		<!-- #ifdef MP -->
		<view class="bottom-submit-btn" @tap.stop="prepareData">提交</view>
		<!-- #endif -->
	</view>
</template>

<script>
import Url from '@/common/http/url.js';
import Tools from '@/utils/Tools.js';
export default {
	data() {
		return {
			navBarBackground: {
				// #ifdef MP
				background: 'linear-gradient(to bottom, #ED4F5D, #FB7A8E)',
				// #endif
				// #ifndef MP
				background: '#fff'
				// #endif
			},

			action: Url.UPLOAD_IMAGE,
			uploadMaxLength: 9,
			editImageIndex: null,

			formData: {},
			keyName: 'iFile',
			content: '',
			contentMaxlength: 200,
			location: {},
			fileList: [],
			videoData: {},
			videoStatus: false
		};
	},
	computed: {
		uploadHeader: function() {
			return {
				Authorization: this.userToken
			};
		},
		imageList: function() {
			const imageList = [];
			if (this.fileList) {
				for (let i = 0; i < this.fileList.length; i++) {
					imageList.push(this.fileList[i].base64 || this.fileList[i].url);
				}
			}

			return imageList;
		},
		cellTitleStyle: function() {
			const cellTitleStyle = {
				fontSize: '32rpx',
				maxWidth: '550rpx',
				display: '-webkit-box',
				'-webkit-box-orient': 'vertical',
				'-webkit-line-clamp': 1,
				overflow: 'hidden',
				wordBreak: 'break-all'
			};
			if (this.location.name) {
				cellTitleStyle.color = '#F85962';
			}
			return cellTitleStyle;
		},
		cellIconStyle: function() {
			if (this.location.name) {
				return { color: '#F85962' };
			}
			return {};
		}
	},
	onLoad() {
		uni.$on('croperComplete', this.croperComplete);
	},
	onReady() {
		this.fileList = this.$refs.uUpload.lists;
	},
	onShow() {
		setTimeout(() => {
			if (!this.location.name) {
				uni.getLocation({
					success: res => {
						if (res.errMsg == 'getLocation:ok') {
							const { latitude, longitude } = res;
							this.location = { latitude, longitude };
						}
					}
				});
			}
		}, 2000);
	},
	onUnload() {
		uni.$off('croperComplete', this.croperComplete);
	},
	methods: {
		back() {
			if (this.content || this.fileList.length > 0) {
				uni.showModal({
					title: '',
					content: '是否退出本次编辑',
					cancelText: '退出',
					confirmText: '留下',
					success: res => {
						if (res.cancel) {
							this.navigateBack();
						}
					}
				});
			} else {
				this.navigateBack();
			}
		},
		beforeUpload(index, list) {
			let width = '';
			let height = '';
			if (list[index].param) {
				const param = list[index].param || {};
				width = param.width || '';
				height = param.height || '';
				this.$set(this.formData, 'param', JSON.stringify(param));
			} else {
				this.formData = {};
			}
			return new Promise((resolve, reject) => {
				uni.getImageInfo({
					src: list[index].base64 || list[index].url,
					success: res => {
						if (width == '' && height == '') {
							width = res.width;
							height = res.height;
						}
						this.$set(this.fileList[index], 'size', { width, height });
						resolve();
					},
					fail: () => {
						this.$set(this.fileList[index], 'size', { width, height });
						resolve();
					}
				});
			});
		},
		deleteUploadItem(index) {
			this.$refs.uUpload.remove(index);
		},
		onUploaded(list) {
			const fileList = [];
			for (let i = 0; i < list.length; i++) {
				console.log(list);
				if (list[i].response.code == 200) {
					const data = list[i].response.data;
					fileList.push({ id: data.file_id, type: 'image', smeta: { size: list[i].size || {} } });
				}
			}
			this.submitTip(fileList);
		},
		croperComplete(data) {
			if (data.fromToken == this.viewToken) {
				this.$set(this.fileList[this.editImageIndex], 'base64', data.res.path);
				this.$set(this.fileList[this.editImageIndex], 'param', data.res.param);
			}
		},
		previewImage(e) {
			const index = e.currentTarget.dataset.index;
			uni.previewImage({
				current: index,
				urls: this.imageList,
				loop: true,
				indicator: 'number'
			});
		},
		editImage(e) {
			this.editImageIndex = e.currentTarget.dataset.index;
			console.log();
			this.navigateTo({
				url:
					'/pageSupport/supplement/cropper' +
					this.$u.queryParams({
						imagePath: this.fileList[this.editImageIndex].url,
						viewToken: this.viewToken,
						aspectRatio: null,
						minBoxWidthRatio: 0.3
					})
			});
		},
		prepareData() {
			if (!this.content && this.fileList.length <= 0 && !this.videoData.src) {
				return false;
			}
			if (this.videoData.src) {
				uni.showLoading({
					title: '上传视频',
					mask: true
				});
				this.uploadVideo();
			} else if (this.fileList.length > 0) {
				uni.showLoading({
					title: '准备数据中...',
					mask: true
				});
				this.$refs.uUpload.upload();
			} else {
				this.submitTip([]);
			}
		},
		submitTip(fileList = []) {
			const postData = {
				content: this.content,
				lng: this.location.longitude || '',
				lat: this.location.latitude || '',
				address: this.location.address || '',
				address_brief: this.location.name || '',
				files: JSON.stringify(fileList)
			};
			if (fileList.length > 0) {
				uni.hideLoading();
			}
			this.$u.api.publishMoment(postData).then(res => {
				if (res.code == 200) {
					Tools.showSuccess('发布成功', () => {
						this.navigateBack();
					});
				}
			});
		},
		deleteLocation() {
			this.location = {};
		},
		chooseLocation() {
			uni.chooseLocation({
				success: res => {
					console.log(res);
					if (res.errMsg == 'chooseLocation:ok') {
						let { address, latitude, longitude, name } = res;
						if (name == '我的位置' || name == '地图位置') {
							name = address;
						}
						this.location = {
							address,
							latitude,
							longitude,
							name
						};
					}
				}
			});
		},
		uploadVideo() {
			const fileList = [];
			this.$u.api.uploadVideo(this.videoData.src).then(res => {
				if (res.code == 200) {
					fileList.push({ id: res.data.file_id, type: 'video', smeta: { size: { height: this.videoData.height, width: this.videoData.width, duration: this.videoData.duration }, cover: res.data.thumb } });
					this.submitTip(fileList);
				} else {
					this.$u.toast('上传视频失败');
				}
			});
		},
		chooseVideo() {
			uni.chooseVideo({
				maxDuration: 30,
				success: res => {
					const { tempFilePath, duration, height, width } = res;
					if (duration > 30) {
						this.$u.toast('小视频时长须小于30秒');
					} else {
						this.videoData = { src: tempFilePath, duration, height, width };
					}
				}
			});
		},
		delVideo() {
			this.videoData = {};
		},
		playVideo() {
			const videoContext = uni.createVideoContext('momentVideo', this);
			videoContext.requestFullScreen({ direction: this.videoData.width > this.videoData.height ? 90 : 0 });
			setTimeout(() => {
				videoContext.play();
			}, 500);
		},
		onVideoFullscreen(e) {
			const fullScreen = e.detail.fullScreen;
			this.videoStatus = fullScreen;
			if (!fullScreen) {
				uni.createVideoContext('momentVideo', this).showStatusBar();
			}
		}
	}
};
</script>

<style lang="scss">
page {
	background: #fff;
}
.upload-chunk {
	padding: 40rpx 24rpx;
	display: flex;
}

.upload-add-btn {
	width: 200rpx;
	height: 200rpx;
	background: rgba(248, 248, 248, 1);
	border-radius: 12rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	flex-direction: column;
	margin-bottom: 20rpx;
	color: #606266;

	.upload-add-icon {
		font-size: 50rpx;
	}
	.upload-add-btn-text {
		margin-top: 10rpx;
		line-height: 40rpx;
		font-size: 24rpx;
	}
}

.hide {
	display: none !important;
}
.video-preview {
	position: relative;

	.video-player {
		z-index: 1;
		left: 0;
		top: 0;
		width: 300rpx;
		height: 300rpx;
		&.horizontal {
			width: 400rpx;
		}
		&.vertical {
			height: 400rpx;
		}
	}
	.video-btn {
		width: 80rpx;
		height: 80rpx;
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		z-index: 10;
	}
	.video-del {
		position: absolute;
		top: 10rpx;
		right: 10rpx;
		z-index: 20;
		background-color: $u-type-error;
		color: #fff;
		border-radius: 100rpx;
		height: 35rpx;
		width: 75rpx;
		text-align: center;
		line-height: 35rpx;
		font-size: 22rpx;
	}
}
.pre-box {
	display: flex;
	align-items: center;
	flex-wrap: wrap;
	.pre-item {
		border-radius: 10rpx;
		height: 200rpx;
		width: 200rpx;
		overflow: hidden;
		position: relative;
		margin-right: 20rpx;
		border-radius: 12rpx;
		overflow: hidden;
		margin-bottom: 20rpx;
	}

	.u-progress {
		position: absolute;
		bottom: 10rpx;
		left: 8rpx;
		right: 8rpx;
		z-index: 9;
		width: auto;
	}

	.pre-item-image {
		width: 200rpx;
		height: 200rpx;
		border-radius: 12rpx;
	}
	.upload-mask,
	.upload-error {
		position: absolute;
		width: 100%;
		height: 100%;
		background-color: rgba($color: #000000, $alpha: 0.2);
		z-index: 20;
		bottom: 0;
		left: 0;
		font-size: 28rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		color: #fff;
	}
	.upload-error {
		z-index: 19;
		background-color: rgba($color: #000000, $alpha: 0.1);
	}

	.edit-btn {
		position: absolute;
		bottom: 10rpx;
		left: 10rpx;
		background-color: $uni-bg-color-mask;
		color: #fff;
		padding: 4rpx 18rpx;
		font-size: 20rpx;
		border-radius: 22rpx;
		z-index: 20;
	}
}
.video-preview,
.pre-box {
	.delete-icon {
		position: absolute;
		top: 10rpx;
		right: 10rpx;
		z-index: 10;
		background-color: $u-type-error;
		border-radius: 100rpx;
		width: 35rpx;
		height: 35rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 20;
	}
}
.divider {
	height: 4rpx;
	width: 750rpx;
	background: rgba(248, 248, 248, 1);
}
.tip-count {
	height: 50rpx;
	display: flex;
	justify-content: flex-end;
	align-items: center;
	padding: 0 20rpx;
	font-size: 24rpx;
	font-weight: 400;
	color: rgba(151, 151, 151, 1);
}
.tip-textarea {
	padding: 20rpx 24rpx;
	font-size: 34rpx;
	line-height: 48rpx;
	height: 350rpx;
}
.tip-textarea-placeholder {
	font-size: 30rpx;
	font-weight: 400;
	color: rgba(151, 151, 151, 1);
}
.bottom-submit-btn {
	width: 600rpx;
	height: 80rpx;
	background: linear-gradient(180deg, rgba(237, 79, 93, 1) 0%, rgba(251, 122, 142, 1) 100%);
	border-radius: 40rpx;
	margin: 130rpx auto 40rpx;
	text-align: center;
	line-height: 80rpx;
	color: #fff;
}
.navbar-submit-btn {
	margin-right: 24rpx;
	border-radius: 3px;
	height: 30px;
	width: 56px;
	color: #fff;
	font-size: 16px;
	display: flex;
	justify-content: center;
	align-items: center;
	background-image: linear-gradient(180deg, rgba(237, 79, 93, 1) 0%, rgba(251, 122, 142, 1) 100%);
}
</style>
